package com.movitech.mobile.ddzy.modules.jobs;

import com.alibaba.fastjson.JSONArray;
import com.movitech.mobile.cz.base.purchase.service.WFlowFormAwardBidService;
import com.movitech.mobile.cz.base.supplier.entity.SSupplierBankAccount;
import com.movitech.mobile.cz.base.supplier.entity.ext.ExtSSuppliers;
import com.movitech.mobile.cz.base.supplier.entity.ext.SupplierSyncVO;
import com.movitech.mobile.cz.base.supplier.service.SSuppliersService;
import com.movitech.mobile.task.CalibrationBidSynRabbitMQProducer;
import com.movitech.mobile.task.SupplierInfoSynRabbitMQProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 供应商数据同步至成本系统
 *
 * @author luodz
 * @version 1.0.0
 * @description 供应商数据同步至成本系统
 * @createTime 2023/04/10
 */
@Component
public class SynSupplier2CostJob {

    @Autowired
    private SSuppliersService sSuppliersService;
    @Autowired
    private SupplierInfoSynRabbitMQProducer supplierInfoSynRabbitMQProducer;

    @Scheduled(cron = "${job.scheduled.supplier2cost}")
    public void syncSupplier2Cost() {
        System.out.println("=============供应商数据同步成本系统定时任务 START===============");
        // 查询合格供应商信息。
        SupplierSyncVO lst = sSuppliersService.getSupplierListForSyncCost();
        List<Map<String, Object>> syncData = new ArrayList<>();

        if (lst.getSuppliersList() != null && lst.getSuppliersList().size() > 0) {

            Map<String, List<SSupplierBankAccount>> bankAccountMap = lst.getSupplierBankAccountList().stream().collect(Collectors.groupingBy(SSupplierBankAccount::getSuppliersId));

            lst.getSuppliersList().forEach(item -> {
                if(bankAccountMap.get(item.getId())!=null){
                    bankAccountMap.get(item.getId()).forEach(ba->{
                        ba.setSuppliersId(item.getCompanyCode());
                    });
                }
                Map<String, Object> map = new HashMap<>();
                map.put("suppliersName", item.getCompanyName());
                map.put("suppliersId", item.getCompanyCode());
                map.put("bankAccount", bankAccountMap.get(item.getId()));
                syncData.add(map);
            });
        }
        if (syncData.size() > 0) {
            supplierInfoSynRabbitMQProducer.producer(JSONArray.toJSONString(syncData));
        }
        System.out.println("=============供应商数据同步成本系统定时任务 END===============");
    }
}
